//
//  GQInviteFriendsController.m
//  GuQu
//
//  Created by HELIUM STAR on 15/5/28.
//  Copyright (c) 2015年 HELIUM STAR. All rights reserved.
//

#import "GQProfileAuthenticationController.h"

@interface GQProfileAuthenticationController () <UITextFieldDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIAlertViewDelegate>

@property (strong, nonatomic) UITextField *textField;
@property (weak, nonatomic) UIImagePickerController *pickerView;
@property (weak, nonatomic) UIButton *addImageBtn;
@property (weak, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) NSMutableArray *imageArr;

@end

@implementation GQProfileAuthenticationController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0];
    self.title = @"申请实名认证";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"distribute_back"] style:UIBarButtonItemStylePlain target:self action:@selector(backToPre)];
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 15)];
    [btn setTitle:@"认证" forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn addTarget:self action:@selector(attestationBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [self setUpChildView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChange:) name:@"UITextFieldTextDidChangeNotification" object:self.textField];
    
}

- (void)textFieldTextDidChange:(NSNotification *)noti
{
    NSInteger count = 5;
    UITextField *textField = (UITextField *)noti.object;
    NSString *text = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage];
    if ([lang isEqualToString:@"zh-Hans"]) {
        UITextRange *selectedRange = [textField markedTextRange];
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        if (!position) {
            if (text.length > count) {
                textField.text = [text substringToIndex:count];
            }
        }else{

        }
    }else{
        textField.text = @"";
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.navigationController.navigationBar.userInteractionEnabled = NO;
    self.addImageBtn.enabled = NO;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    self.navigationController.navigationBar.userInteractionEnabled = YES;
    self.addImageBtn.enabled = YES;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UITextFieldTextDidChangeNotification" object:self.textField];
}

- (void)backToPre
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)attestationBtnDidClick
{
    
    
    NSString *text = self.textField.text;
    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    self.textField.text = text;
        
    if(text.length > 0 && self.imageArr.count > 1){
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"申请实名认证后真实姓名将代替原来用户名" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alertView.delegate = self;
        [alertView show];
    }else{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"请填写真实的姓名和资料" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        alertView.delegate = self;
        [alertView show];
    }
}

- (void)setUpChildView
{
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, kNavigatationBarHeight, self.view.width, 44)];
    textField.backgroundColor = [UIColor whiteColor];
    self.textField = textField;
    textField.placeholder = @"真实姓名";
    UIView *leftAccessoryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, textField.height)];
    textField.leftView = leftAccessoryView;
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.delegate = self;
    [self.view addSubview:textField];
    
    //真实资料照片
    UILabel *infoLabel = [[UILabel alloc] init];
    infoLabel.x = 10;
    infoLabel.width = self.view.width;
    infoLabel.height = 16;
    infoLabel.y = CGRectGetMaxY(textField.frame) + 10;
    infoLabel.text = @"资料上传(最多上传5张)";
    infoLabel.font = [UIFont systemFontOfSize:12];
    infoLabel.textColor = [UIColor blackColor];
    [self.view addSubview:infoLabel];
    
    UIScrollView *includeView = [[UIScrollView alloc] init];
    includeView.x = 0;
    includeView.width = self.view.width;
    includeView.height = 110;
    includeView.y = CGRectGetMaxY(infoLabel.frame);
    includeView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:includeView];
    self.scrollView = includeView;
    
    UIButton *addImageBtn = [[UIButton alloc] init];
    addImageBtn.x = 15;
    addImageBtn.width = 80;
    addImageBtn.height = 80;
    addImageBtn.y = (includeView.height - addImageBtn.height) / 2;
    self.addImageBtn = addImageBtn;
    [self.imageArr addObject:addImageBtn];
    
    [addImageBtn addTarget:self action:@selector(addBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    [addImageBtn setImage:[UIImage imageNamed:@"distribute_add"] forState:UIControlStateNormal];
    [includeView addSubview:addImageBtn];
    
    UIWebView *webView = [[UIWebView alloc] init];
    webView.x = 10;
    webView.scrollView.bounces = NO;
    webView.width = self.view.width - 10 * 2;
    webView.height = 200;
    webView.y = CGRectGetMaxY(includeView.frame) + 20;
    [self.view addSubview:webView];
    NSString *str = @"<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head><body style=\"background-color:#F0F0F0\"><div style=\"font-size:18px\">实名认证的特权：</div><div style=\"font-size:13px\">1：昵称附近有独特的认证标识</div><div style=\"font-size:13px\">2：增加用户的可信度</div><br/><div style=\"font-size:18px\">实名认证的条件：</div><div style=\"font-size:13px\">1：必须提供身份证正反照。</div><div style=\"font-size:13px\">2：最好提供手持证件的照。</div><div style=\"font-size:13px\">3：最好能提供证明身份的证书或营业执照。</div><div style=\"font-size:13px\">4：最好是某个领域的行家，能发出优质内容。</div><div style=\"font-size:13px\">5：最好很有分享功能，活跃度高。</div></body></html>";
    [webView loadHTMLString:str baseURL:nil];
    
}

- (void)willPresentAlertView:(UIAlertView *)alertView
{
    NSLog(@"%ld", alertView.subviews.count);
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"%ld", buttonIndex);
    if (buttonIndex == 1) {
        UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
        pickerController.delegate = self;
        pickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        pickerController.allowsEditing = YES;
        [self presentViewController:pickerController animated:YES completion:nil];
        self.pickerView = pickerController;
    }
}

- (void)addBtnDidClick
{
    if (self.imageArr.count >= 6) {
        return;
    }
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"相册", nil];
    [actionSheet showInView:self.view];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = info[UIImagePickerControllerEditedImage];
    [self dismissViewControllerAnimated:YES completion:nil];
    [self refreshScrollViewImage:image];
}

#pragma mark - 刷新UIScrollView
- (void)refreshScrollViewImage:(UIImage *)image
{
    CGFloat addImageMargin = 5;
    
    CGRect currentAddBtnFrame = self.addImageBtn.frame;
    CGFloat addX = self.addImageBtn.x + self.addImageBtn.width + addImageMargin;
    CGFloat addMaxX = addX + self.addImageBtn.width + 10;
    self.scrollView.contentSize = CGSizeMake(addMaxX, 0);
    self.addImageBtn.x = addX;
    if (addMaxX > self.scrollView.width) {
        self.scrollView.contentOffset = CGPointMake(addMaxX - self.scrollView.width, 0);
    }
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    [self.scrollView addSubview:imageView];
    imageView.alpha = 0;
    imageView.frame = currentAddBtnFrame;
    imageView.layer.borderWidth = 1;
    imageView.userInteractionEnabled = YES;
    imageView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    NSLog(@"%@", imageView);
    
    CGFloat cancleWidth = 18;
    UIButton *cancleImageBtn = [[UIButton alloc] init];
    cancleImageBtn.x = imageView.width - cancleWidth;
    cancleImageBtn.y = 0;
    cancleImageBtn.width = cancleWidth;
    cancleImageBtn.height = cancleWidth;
    
    [cancleImageBtn setImage:[UIImage imageNamed:@"distribute_delete"] forState:UIControlStateNormal];
    [cancleImageBtn addTarget:self action:@selector(cancleBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [imageView addSubview:cancleImageBtn];
    
    [self.imageArr insertObject:imageView atIndex:self.imageArr.count - 1];
    [UIView animateWithDuration:0.3 delay:0.3 options:0 animations:^{
        imageView.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
    
}

#pragma mark - 取消按钮事件
- (void)cancleBtnDidClick:(UIButton *)btn
{
    NSInteger index = [self.imageArr indexOfObject:(UIImageView *)btn.superview];
    [btn.superview removeFromSuperview];
    [self.imageArr removeObject:btn.superview];
    NSInteger count = self.imageArr.count;
    for (NSInteger i = index; i < count; i++) {
        UIView *view1 = self.imageArr[i];
        
        [UIView animateWithDuration:0.3 animations:^{
            view1.x -= view1.width + 5;
        }];
    }
    UIView *lastObject = [self.imageArr lastObject];
    CGFloat btnMaxX = CGRectGetMaxX(lastObject.frame) + 10;
    self.scrollView.contentSize = CGSizeMake(btnMaxX, 0);
    if (btnMaxX - self.scrollView.width > 0) {
        self.scrollView.contentOffset =CGPointMake(btnMaxX - self.scrollView.width, 0);
    }else{
        self.scrollView.contentOffset =CGPointMake(0, 0);
    }
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}

- (NSMutableArray *)imageArr
{
    if (_imageArr == nil) {
        _imageArr = [NSMutableArray array];
    }
    return _imageArr;
}

@end
